#!/usr/bin/env python

# Copyright 2012 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Street Identity Scope Utils."""

import re

__author__ = 'Maciej Machulak'
__maintainer__ = 'Maciej Machulak'
__email__ = 'mmachulak@google.com'

__copyright__ = 'Copyright 2012, Google Inc.'
__license__ = 'Apache License 2.0'
__version__ = '0.2'
__status__ = 'Prototype'

_SCOPE_PREFIX = 'https://www.googleapis.com/auth/'
_STREETIDENTITY_SCOPES_READ = [
  _SCOPE_PREFIX + 'streetidentity.read',
  _SCOPE_PREFIX + 'verifiedage.read',
  _SCOPE_PREFIX + 'verifiedgender.read']
_STREETIDENTITY_SCOPES_WRITE = [
  _SCOPE_PREFIX + 'streetidentity.write',
  _SCOPE_PREFIX + 'verifiedage.write',
  _SCOPE_PREFIX + 'verifiedgender.write']
_STREETIDENTITY_SCOPES_ALL = []
_STREETIDENTITY_SCOPES_ALL.extend(_STREETIDENTITY_SCOPES_READ)
_STREETIDENTITY_SCOPES_ALL.extend(_STREETIDENTITY_SCOPES_WRITE)

_UNPREFIXED_STREETIDENTITY_SCOPES_READ = [
  'streetidentity.read',
  'verifiedage.read',
  'verifiedgender.read']

_UNPREFIXED_STREETIDENTITY_SCOPES_WRITE = [
  'streetidentity.write',
  'verifiedage.write',
  'verifiedgender.write']

_UNPREFIXED_STREETIDENTITY_SCOPES_ALL = _UNPREFIXED_STREETIDENTITY_SCOPES_READ
_UNPREFIXED_STREETIDENTITY_SCOPES_ALL.\
extend(_UNPREFIXED_STREETIDENTITY_SCOPES_WRITE)


def get_unprefixed_scopes(scopes, prefix = _SCOPE_PREFIX):

  unprefixed_scopes = []
  for scope in scopes:
    match = re.search(r'(^' + prefix + ')([a-zA-Z0-9_.]*)',scope)
    if match:
      unprefixed_scopes.append(match.group(2))
  return unprefixed_scopes


def get_unprefixed_streetidentity_scopes(scopes):
  unprefixed_scopes = get_unprefixed_scopes(scopes)
  for scope in unprefixed_scopes:
    if scope not in _UNPREFIXED_STREETIDENTITY_SCOPES_ALL:
      unprefixed_scopes.remove(scope)
  return unprefixed_scopes


def get_prefixed_scopes(scopes, prefix = _SCOPE_PREFIX):

  prefixed_scopes = []
  for scope in scopes:
    scope = ''.join([prefix,scope])
    prefixed_scopes.append(scope)
  return prefixed_scopes


def filter_scopes(scopes, target_scopes = _STREETIDENTITY_SCOPES_READ):
  """Returns a list of filtered scopes."""

  temp_scopes = []
  for scope in scopes:
    if scope in target_scopes:
      temp_scopes.append(scope)
  return temp_scopes
